<template>
	<div class="home" ref="home">
		<div>
			<Header v-show="headerShow"/>
			<div class="home-main">
				<Swipe :swipeList="bannerList" key="home-swipe"/>
				<Nav/>
				<Bargain :bargainList="bargainList"/>
				<Special :specialList="specialList"/>
				<Recommend :recommendList="recommendList"/>
			</div>
		</div>
	</div>
</template>

<script>
	import Product from '../services/product';
	import News from '../services/news';
	import Throttle from '@/utils/throttle';
	import Header from '#/Home/Header';
	import Swipe from '#/Public/Swipe';
	import Nav from '#/Home/Nav';
	import Bargain from '#/Home/Bargain';
	import Special from '#/Home/Special';
	import Recommend from '#/Home/Recommend';
	import {mapActions, mapState} from 'vuex';

	const _product = new Product();
	const _news = new News();

	export default {
		name: 'Home',
		created() {
			this.getBanner();
			this.getBargainList();
			this.getSpecialList();
			this.getRecommendList();
			this.throttle = new Throttle(this.scrollHeaderShow);
		},
		mounted() {
			this.parentMain = document.getElementsByTagName('main')[0];
			this.$refs['home'].addEventListener('touchmove', this.handleScroll);
			this.parentMain.addEventListener('scroll', this.handleScroll)
		},
		data() {
			return {
				bannerList: [],
				headerShow: false,
				msg: ''
			}
		},
		computed: {
			...mapState(['bargainList', 'specialList', 'recommendList'])
		},
		methods: {
			...mapActions(['setBargainList', 'setSpecialList', 'setRecommendList']),
			scrollHeaderShow() {
				let scrollTop = document.getElementsByTagName('main')[0].scrollTop;
				let swipe = document.getElementsByClassName('h-swipe-container')[0];
				let swipeHeight = 0;
				if (swipe) {
					swipeHeight = swipe.clientHeight || swipe.offsetHeight;
				}
				this.headerShow = scrollTop >= swipeHeight;
			},
			handleScroll() {
				this.throttle.throttle()
			},
			getBanner() {
				_product.getBanner().then(res => {
					this.bannerList = res.data;
				});
			},
			getBargainList() {
				_product.getBargainList().then(res => {
					this.setBargainList(res.data);
				})
			},
			getSpecialList() {
				_news.getSpecialList().then(res => {
					this.setSpecialList(res.data);
				})
			},
			getRecommendList() {
				_product.getRecommendList().then(res => {
					this.setRecommendList(res.data);
				})
			}
		},
		components: {
			Header,
			Swipe,
			Nav,
			Bargain,
			Special,
			Recommend
		},
		beforeDestroy() {
			this.$refs['home'].removeEventListener('touchmove', this.handleScroll);
			this.parentMain.removeEventListener('scroll', this.handleScroll);
			this.throttle.off();
			this.throttle = null;
		}
	}
</script>
